﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using StructureMap;
using Masood.SharePoint.ProcessingTimerJob.Interfaces;

namespace Masood.SharePoint.ProcessingTimerJob
{
    public class ProcessingTimerJob : SPJobDefinition
    {
        public ProcessingTimerJob() : base() 
        {
            
        }

        public ProcessingTimerJob(SPWebApplication webApp, string jobName)
            : base(jobName, webApp, null, SPJobLockType.Job)
        {
            this.Title = jobName;            
        }

        private void InitContainer()
        {
            ObjectFactory.Initialize(x =>
                x.AddConfigurationFromXmlFile("Masood.SharePoint.ProcessingTimerJob.StructureMap.config"));
        }

        public override void Execute(Guid targetInstanceId)
        {
            InitContainer();

            StringBuilder logs = new StringBuilder();
            bool errorOccurred = false;
            try
            {
                //get the repository instance from the container
                IRepository repo = ObjectFactory.GetInstance<IRepository>();

                logs.AppendLine(string.Format("Reading data from '{0}' repository", repo.RepositoryType));
                
                List<Item> itemsToBeProcessed = repo.GetAll();
                logs.AppendLine(string.Format("Total items:{0} found for processing...", itemsToBeProcessed.Count));
                
                foreach (Item item in itemsToBeProcessed)
                {
                    //process according to your requirement
                    logs.AppendLine(string.Format("Processing item Id:'{0}', Title:'{1}' ...", item.Id, item.Title));
                }
            }
            catch (Exception ex)
            {
                logs.AppendLine(string.Format("Error: {0}", ex.Message));
                logs.AppendLine(ex.StackTrace);
                errorOccurred = true;
            }

            if (errorOccurred)
                Logger.LogError(logs.ToString(), this.Title);
            else
                Logger.LogInformation(logs.ToString(), this.Title);
        }
    }
}
